<template>
  <div>
    <el-form label-width="80px" v-model="filterForm" @submit.native.prevent>
      <el-row style="line-height: 40px" type="flex" align="middle">
        <el-col :span="6">
          <el-form-item label="关键字">
            <el-input
              @keyup.13.native="btnSearch"
              v-model="filterForm.searchKey"
              placeholder="请输入姓名"
              size="mini"
            >
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="所属机构">
            <el-select
              v-model="filterForm.institutionId"
              placeholder="请选择所属机构"
              :disabled="ifFixedOrg"
              size="mini"
            >
              <el-option
                v-for="item in institutions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-row style="height: 40px" type="flex" align="middle" justify="end">
            <div @click="clickUnfold" class="expansion" style="margin-right: 10px">
              <font-awesome-icon v-if="!showMoreSearchFilter" :icon="['fas', 'angle-down']">
              </font-awesome-icon>
              <font-awesome-icon v-else :icon="['fas', 'angle-up']"> </font-awesome-icon>
            </div>
            <el-button @click="btnSearch" size="mini">
              <font-awesome-icon :icon="['fas', 'search']"></font-awesome-icon>
            </el-button>
            <el-button @click="jumpUserAdd" type="primary" size="mini"> 新增用户 </el-button>
          </el-row>
        </el-col>
      </el-row>
      <el-row style="line-height: 40px" type="flex" align="middle">
        <el-col :span="24">
          <el-form-item label="角色">
            <el-checkbox-group v-model="filterForm.checkedRole" style="height: 40px" size="mini">
              <el-checkbox v-for="identity in roleList" :label="identity.id" :key="identity.id">
                {{ identity.name }}
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-col>
      </el-row>
      <div v-show="showMoreSearchFilter">
        <el-row style="line-height: 40px" type="flex" align="middle">
          <el-col :span="8" class="flat">
            <el-form-item label="注册时间">
              <el-date-picker
                v-model="filterForm.createdRange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                class="time-picker-form"
                type="daterange"
                size="mini"
                @change="pickerChangeFn"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8" class="flat">
            <el-form-item label="用户状态">
              <el-checkbox-group v-model="filterForm.checkedStatus" style="height: 40px">
                <el-checkbox
                  v-for="userStatus in statusList"
                  :label="userStatus.value"
                  :key="userStatus.value"
                >
                  {{ userStatus.label }}
                </el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row style="line-height: 40px" type="flex" align="middle">
          <el-col :span="8" class="flat">
            <el-form-item label="职级">
              <el-select
                v-model="filterForm.positionList"
                placeholder="请选择"
                class="picker-form"
                size="mini"
                multiple
              >
                <el-option v-for="t in positionList" :key="t.id" :label="t.name" :value="t.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8" class="flat">
            <el-form-item label="职称">
              <el-select
                v-model="filterForm.medicalTitleList"
                placeholder="请选择"
                class="picker-form"
                size="mini"
                multiple
              >
                <el-option v-for="t in medicalTitleList" :key="t.id" :label="t.name" :value="t.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row style="line-height: 40px" type="flex" align="middle">
          <el-col :span="8" class="flat">
            <el-form-item label="所属区域">
              <el-cascader
                v-model="filterForm.area"
                :options="areaList"
                placeholder="请选择搜索的区域"
                :props="areaProps"
                class="picker-form"
                size="mini"
                clearable
              >
              </el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="认证通过">
              <el-checkbox-group v-model="filterForm.checkedCertification" size="mini">
                <el-checkbox
                  v-for="item in certificationList"
                  :label="item.value"
                  :key="item.value"
                >
                  {{ item.label }}
                </el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
        </el-row>
      </div>
    </el-form>
    <!-- 列表数据 -->
    <div>
      <el-row>
        <base-table
          v-loading="!userTable.isReady"
          ref="userTable"
          :data="userTable.data"
          :header="userTable.header"
          :operation="userTable.operation"
          :pageInfo="userTable.pageInfo"
          :pageSizes="[10, 15, 20]"
          :cellStyleFunc="userTableCellStyleFunc"
          :buttonVisibleFunc="userTableButtonVisibleFunc"
          @handleClick="userTableButtonClick"
          @pageJumpTo="pageJumpTo"
          @sizeChange="pageSizeChange"
        >
        </base-table>
      </el-row>
    </div>
  </div>
</template>

<script>
import moment from 'moment'
import BaseTable from '@/templates/components/BaseTable'
import _ from 'lodash'

export default {
  name: 'UserList',
  props: ['ifInstitution'],
  components: {
    BaseTable
  },
  data() {
    return {
      institutions: [],
      uArgs: this.$store.getters.getUArgs,
      filterForm: {
        searchKey: '',
        institutionName: '',
        checkedRole: [],
        createdRange: [],
        checkedStatus: [0],
        positionList: [],
        medicalTitleList: [],
        area: [],
        checkedCertification: []
      },

      filterCurrent: {},

      dictionaryMap: [
        {
          code: 'PostKind',
          array: 'positionList'
        },
        {
          code: 'TitleForClinic',
          array: 'medicalTitleList'
        }
      ],
      roleList: [],
      statusList: [
        {
          label: '正常',
          value: 0
        },
        {
          label: '冻结',
          value: 1
        }
      ],
      positionList: [],
      medicalTitleList: [],
      certificationList: [
        {
          label: '身份认证',
          value: 'idCardStatus'
        },
        {
          label: '资质认证',
          value: 'qualityStatus'
        }
      ],
      // 搜索的地区数据
      areaList: [],

      showMoreSearchFilter: false,
      userTable: {
        isReady: false,
        data: [],
        header: [
          {
            prop: 'name',
            label: '姓名',
            width: '80'
          },
          {
            prop: 'genderName',
            label: '性别',
            width: '80'
          },
          {
            prop: 'phone',
            label: '联系电话',
            width: '120'
          },
          {
            prop: 'account',
            label: '登录名',
            width: '100'
          },
          {
            prop: 'institutionName',
            label: '所属机构',
            width: '120'
          },
          {
            prop: 'positionName',
            label: '职级',
            width: '80'
          },
          {
            prop: 'medicalTitleName',
            label: '职称',
            width: '80'
          },
          {
            prop: 'roleString',
            label: '角色',
            width: '100'
          },
          {
            prop: 'createTime',
            label: '注册时间',
            width: '140'
          },
          {
            prop: 'area',
            label: '所在地'
          },
          {
            label: '实名认证',
            prop: 'idCardStatusName',
            isButton: true,
            functionKey: 'showIDCardDialog'
          },
          {
            label: '资质认证',
            prop: 'qualityStatusName',
            isButton: true,
            functionKey: 'showQualificationDialog'
          },
          {
            prop: 'statusName',
            label: '用户状态'
          }
        ],
        operation: [
          {
            label: '冻结',
            functionKey: 'userTableFrozen'
          },
          {
            label: '解冻',
            color: 'red',
            functionKey: 'userTableUnfrozen'
          },
          {
            label: '管理',
            functionKey: 'userTableManage'
          },
          {
            label: '重置密码',
            functionKey: 'userTableResetPwd'
          }
        ],
        pageInfo: {
          size: 15,
          page: 1,
          total: 0
        }
      },
      // 确定了的时间区域
      createdRange: [],
      areaProps: {
        value: 'id',
        label: 'name',
        children: 'childrenList'
      },
      // 确定了的地区区域,根据接口的要求，搜索的时候还要
      // 转换数组为3个对象
      areaSelect: []
    }
  },
  computed: {
    ifFixedOrg() {
      if (this.ifInstitution) {
        return true
      }
      return false
    }
  },
  mounted() {
    // 数据初始化
    // 获取用户的数据列表
    this.btnSearch()
    // 行政区域数据初始化

    this.getAreaList()
    this.getRoleList()

    this.dictionaryMap.forEach(map => {
      this.$axios({
        method: 'GET',
        url: '/dicts/list',
        params: {
          code: map.code,
          page: 0,
          size: 99
        }
      }).then(res => {
        if (res && res.data.code === 200) {
          this[map.array] = _.clone(res.data.data)
        }
      })
    })
    this.institutionTableRequest()
  },
  methods: {
    pickerChangeFn(value) {
      // 日期选择器改变事件 ~ 解决日期选择器清空 值不清空的问题
      if (value === null) {
        this.filterForm.createdRange = []
      }
    },
    // 获取所有机构数据
    institutionTableRequest() {
      const pageInfo = {
        page: 0,
        size: 999
      }
      const filter = _.assign({}, pageInfo)
      try {
        this.$axios({
          method: 'POST',
          url: '/institutions/search',
          data: filter
        }).then(res => {
          if (res && res.data.code === 200) {
            // 数据处理
            this.institutions = []
            if (this.ifInstitution) {
              const institution = {
                id: this.$store.state.institution.id,
                name: this.$store.state.institution.name
              }
              console.log('institution', institution, this.$store.state)
              this.filterForm.institutionName = institution.name
              this.institutions.push(institution)
            } else {
              res.data.data.forEach(t => {
                const institution = {
                  id: t.id,
                  name: t.name
                }
                this.institutions.push(institution)
              })
            }
          }
        })
      } catch (e) {
        this.$message.warning('请求失败')
      }
    },
    // 获取行政区域数据
    getAreaList() {
      this.$axios({
        method: 'get',
        url: '/provinces',
        params: {}
      }).then(res => {
        if (res && res.data.code === 200) {
          this.areaList = _.clone(res.data.data)
        }
      })
    },
    // 获取角色数据
    getRoleList() {
      this.$axios({
        method: 'GET',
        url: '/roles',
        params: {
          size: 99
        }
      }).then(res => {
        if (res && res.data.code === 200) {
          res.data.data.forEach(t => {
            this.roleList.push({
              id: t.id,
              name: t.name
            })
          })
        }
      })
    },
    userTableCellStyleFunc({ row, column }) {
      const baseStyle = {
        padding: '3px 0',
        'border-right': '1px solid #ffffff',
        'font-size': '14px'
      }
      if (column.label === '状态') {
        if (row.status === 1) {
          baseStyle.color = 'red'
        }
        if (row.status === 0) {
          baseStyle.color = '#409eff'
        }
      }
      return baseStyle
    },
    userTableButtonVisibleFunc(key, row) {
      switch (key) {
        case 'userTableFrozen':
          return row.status === 0
        case 'userTableUnfrozen':
          return row.status === 1
        default:
          return true
      }
    },
    userTableButtonClick(functionKey, row) {
      this[functionKey](row)
    },
    // 获取列表数据
    userTableRequest() {
      this.userTable.isReady = false
      const pageInfo = {
        page: this.userTable.pageInfo.page - 1,
        size: this.userTable.pageInfo.size
      }
      const filter = _.assign({}, pageInfo, this.filterCurrent)
      try {
        this.$axios({
          method: 'POST',
          url: '/users/search',
          data: filter
        }).then(res => {
          if (res && res.data.code === 200) {
            // 分页处理
            this.userTable.pageInfo = {
              total: res.data.pageInfo.total,
              page: res.data.pageInfo.page + 1,
              size: res.data.pageInfo.size
            }
            // 数据处理
            this.userTable.data = []
            res.data.data.forEach((t, index) => {
              const user = {
                index,
                id: t.id,

                name: t.name,
                genderName: t.genderName,
                jobNumber: t.jobNumber,
                phone: t.phone,
                account: t.account,
                institutionName: t.institutionName,
                positionName: t.positionName,
                medicalTitleName: t.medicalTitleName,
                createTime: moment(t.createTime).format('YYYY-MM-DD'),
                statusName: t.status ? '冻结' : '正常',
                area: t.area,
                roleString: '',
                idCardStatusName: '',
                qualityStatusName: '',

                roleList: t.roles,
                status: t.status,
                // 身份认证信息
                idCardStatus: t.idCardStatus,
                practice: {
                  code: _.get(t, 'practiceCode', ''),
                  urlF: _.get(t, 'practiceUrlF', ''),
                  urlR: _.get(t, 'practiceUrlR', '')
                },
                // 资质认证信息
                qualityStatus: t.qualityStatus,
                qualification: {
                  code: _.get(t, 'qualificationCode', ''),
                  urlF: _.get(t, 'qualificationUrlF', ''),
                  urlR: _.get(t, 'qualificationUrlR', '')
                }
              }

              switch (user.idCardStatus) {
                case -1:
                  user.idCardStatusName = '未通过'
                  break
                case 0:
                  user.idCardStatusName = '待确认'
                  break
                case 1:
                  user.idCardStatusName = '已通过'
                  break
                default:
                  break
              }

              switch (user.qualityStatus) {
                case -1:
                  user.qualityStatusName = '未通过'
                  break
                case 0:
                  user.qualityStatusName = '待确认'
                  break
                case 1:
                  user.qualityStatusName = '已通过'
                  break
                default:
                  break
              }

              user.roleList.forEach(role => {
                user.roleString += role.name
                user.roleString += ' '
              })

              this.userTable.data.push(user)
            })
          }

          this.userTable.isReady = true
        })
      } catch (e) {
        this.userTable.isReady = true
        this.$message.warning('请求失败')
      }
    },
    jumpUserAdd() {
      this.$store.commit('setUArgs', {
        isPlatformManage: this.uArgs.isPlatformManage,
        isAddNew: 1,
        institutionId: this.$store.state.institution.id
      })
      this.$router.push(`${this.$route.path}/add`)
    },
    userTableManage(user) {
      this.$store.commit('setUArgs', {
        isPlatformManage: this.uArgs.isPlatformManage,
        isAddNew: 0,
        userId: user.id,
        institutionId: this.$store.state.institution.id
      })
      this.$router.push(`${this.$route.path}/edit`)
    },
    // 分页调转
    pageJumpTo(val) {
      this.userTable.pageInfo.page = val
      // 获取用户的数据列表
      this.userTableRequest()
    },
    // 分页调转
    pageSizeChange(val) {
      this.userTable.pageInfo.size = val
      // 获取用户的数据列表
      this.userTableRequest()
    },
    // 用户冻结
    userTableFrozen(val) {
      this.$confirm('是否冻结该用户？点击确认继续，点击取消退出', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$axios({
          method: 'PUT',
          url: `/users/lock/${val.id}`
        }).then(res => {
          if (res.data.code === 200) {
            this.$message.success('冻结成功')
            this.userTableRequest()
          } else {
            this.$message.warning(res.data.message)
          }
        })
      })
    },
    userTableUnfrozen(val) {
      this.$confirm('是否解冻该用户？点击确认继续，点击取消退出', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$axios({
          method: 'PUT',
          url: `/users/unlock/${val.id}`
        }).then(res => {
          if (res.data.code === 200) {
            this.$message.success('解冻成功')
            this.userTableRequest()
          } else {
            this.$message.warning(res.data.message)
          }
        })
      })
    },
    userTableResetPwd(val) {
      this.$confirm('是否重置密码？点击确认继续，点击取消退出', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        try {
          this.$axios({
            method: 'PUT',
            url: `/reset-password/${val.id}`
          }).then(res => {
            if (res.data.code === 200) {
              this.$message.success('重置密码成功')
            }
          })
        } catch (e) {
          console.log('请求失败')
        }
      })
    },
    showIDCardDialog() {
      // todo 身份认证
    },
    showQualificationDialog() {
      // todo 资质认证
    },
    clickUnfold() {
      this.showMoreSearchFilter = !this.showMoreSearchFilter
    },
    btnSearch() {
      // 按照接口返回数据格式定义对象
      this.filterCurrent = {}

      const tempFilter = {}

      if (this.filterForm.searchKey) {
        tempFilter.name = this.filterForm.searchKey
      }
      if (this.filterForm.institutionId) {
        // tempFilter.institutionName = this.filterForm.institutionName
        tempFilter.institutionId = this.filterForm.institutionId
      }
      if (this.filterForm.checkedRole.length > 0) {
        tempFilter.roleIdList = []
        this.filterForm.checkedRole.forEach(id => {
          tempFilter.roleIdList.push(id)
        })
      }
      if (this.filterForm.createdRange === null) {
        this.filterForm.createdRange = []
      }
      if (this.filterForm.createdRange.length > 0) {
        const [createTimeStart, createTimeEnd] = this.filterForm.createdRange
        tempFilter.createTimeStart = moment(createTimeStart).format('YYYY-MM-DD hh:mm:ss')
        tempFilter.createTimeEnd = moment(createTimeEnd).format('YYYY-MM-DD hh:mm:ss')
      }
      if (this.filterForm.checkedStatus.length > 0) {
        tempFilter.statusList = []
        this.filterForm.checkedStatus.forEach(id => {
          tempFilter.statusList.push(id)
        })
      }

      tempFilter.positionList = _.clone(this.filterForm.positionList)
      tempFilter.medicalTitleList = _.clone(this.filterForm.medicalTitleList)

      const areaLevelList = ['provinceId', 'cityId', 'countyId']
      this.filterForm.area.forEach((id, index) => {
        tempFilter[areaLevelList[index]] = id
      })

      this.filterForm.checkedCertification.forEach(key => {
        tempFilter[key] = 1
      })

      // 是否为平台 - 用户管理页面
      if (!this.uArgs.isPlatformManage) {
        tempFilter.institutionId = this.uArgs.institutionId
      }

      this.filterCurrent = _.clone(tempFilter)
      this.userTable.pageInfo.page = 1
      this.userTableRequest()
    }
  }
}
</script>

<style scoped>
.expansion {
  font-size: 28px;
  color: #266eff;
  cursor: pointer;
}
</style>
